<template>
  <template v-if="imgLoading">
    <div
      v-loading="imgLoading"
      :class="[{ 'rounded-full': round }, classNames]"
      :style="{ width: xxToRem(width), height: xxToRem(height) }"
    ></div>
  </template>
  <img
    v-else
    class="image"
    :src="src"
    :alt="alt"
    :loading="loading"
    :width="width"
    :height="height"
    :class="[{ 'rounded-full': round }, classNames]"
    @error="
      emits('error', $event);
      imgLoading = false;
    "
    @load="
      emits('load', $event);
      imgLoading = false;
    "
  />
</template>

<script setup lang="ts">
import { computed, ref } from 'vue';
import { TinyLoading } from '@opentiny/vue';
import { xxToRem } from '@/utils';
const vLoading = TinyLoading.directive;
const props = withDefaults(
  defineProps<{
    src: string;
    alt?: string;
    lazy?: boolean;
    width?: number | string;
    height?: number | string;
    round?: boolean;
    fit?: string;
  }>(),
  {
    src: '',
    alt: '',
    lazy: false,
    width: 70,
    height: 70,
    round: false,
    fit: 'cover',
  }
);
const loading = computed(() => (props.lazy ? 'lazy' : undefined));
const emits = defineEmits(['error', 'load']);

const imgLoading = ref(true);
const classMap = {
  fit: {
    cover: 'object-cover',
    contain: 'object-contain',
    fill: 'object-fill',
    none: 'object-none',
    scaleDown: 'object-scale-down',
  },
};
const classNames = computed(() => {
  const { fit } = props;
  return classMap.fit[fit as keyof typeof classMap.fit];
});

const loadImg = () =>{
  const img = new Image();
  img.src = props.src;
  img.onload = () =>{
    imgLoading.value = false;
  }
  img.onerror = () =>{
    imgLoading.value = false;
  }
  return img;
}
loadImg()
</script>

<style scoped lang="css"></style>
